<?php

declare(strict_types=1);

namespace App\Http\Api;

use App\Model\User\User;
use App\Repository\User\UserRepository;
use Exception;
use Hyperf\Context\Context;

/**
 * 当前用户
 * Class CurrentUser
 */
final class CurrentUser
{
    public function __construct(
        protected readonly UserRepository $repository
    )
    {
    }

    protected const CONTEXT_KEY = 'user';

    /**
     * 设置当前用户
     * @param int $uid
     * @return void
     * @throws Exception
     */
    public function setUser(int $uid): void
    {
        $user = $this->repository->findByFilter(['id' => $uid, 'status' => 1]);
        if (!$user) {
            throw new Exception('当前用户不存在');
        }

        Context::set(self::CONTEXT_KEY, $user);


    }

    /**
     * 获取当前用户
     * @return User
     * @throws Exception
     */
    public function getUser(): User
    {
        $user = Context::get(self::CONTEXT_KEY);
        if (!$user) {
            throw new Exception('用户未登录或上下文中不存在');
        }
        return $user;
    }

    /**
     * 获取当前用户ID
     * @return mixed
     * @throws Exception
     */
    public function getId(): mixed
    {
        $user = Context::get(self::CONTEXT_KEY);
        if (!$user) {
            throw new \Exception('用户未登录或上下文不存在');
        }
        return $user->id;
    }

    public function logout()
    {

    }
}
